﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Threading;

using System.Deployment;
using System.Deployment.Application;

namespace GCGMain
{
    /// <summary>
    /// Logique d'interaction pour Splash.xaml
    /// </summary>
    public partial class Splash : Window
    {
        static GCGDataBaseTableLib.EmployeTable TEmploye = new GCGDataBaseTableLib.EmployeTable();
        
        private readonly BackgroundWorker worker = new BackgroundWorker();
        public string state = "";

        public Splash()
        {
            InitializeComponent();
            worker.DoWork += worker_DoWork;
            worker.RunWorkerCompleted += worker_RunWorkerCompleted;
            worker.ProgressChanged += worker_ProgressChanged;
        }

        private void FrmSplash_Loaded(object sender, RoutedEventArgs e)
        {

            worker.WorkerReportsProgress = true;
            worker.RunWorkerAsync();
            lblStatus.Content = "Vérification du serveur ...";
            
        }

        private void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            worker.ReportProgress(0);
            loadingConfig();

            worker.ReportProgress(25);
            if (GCGGeneralLib.GeneralVar.DbUser == "solut953_genik")
            {
                state = "new";

            }
            else
            {
                worker.ReportProgress(50);
                if (GCGGeneralLib.DataBaseConnection.DbTestConnection(Properties.Settings.Default.connectionString))
                {
                    state = "ok";   
                }
                else
                {
                      MessageBoxResult resultat = System.Windows.MessageBox.Show("Une erreur s'est produite lors de la tentative connection, Vérifier les paramètres ?", "Attention", MessageBoxButton.YesNo);
                      if (resultat == MessageBoxResult.Yes)
                      {
                          state = "bad";
                      }
                      else
                      {
                          System.Windows.Application.Current.Shutdown();
                      }
                }
            }
            worker.ReportProgress(100);
        }


        private void worker_RunWorkerCompleted(object sender,RunWorkerCompletedEventArgs e)
        {
            if (state == "new")
            {
                lblPass.Visibility = System.Windows.Visibility.Visible;
                lblServer.Visibility = System.Windows.Visibility.Visible;
                lblTable.Visibility = System.Windows.Visibility.Visible;
                lblUser.Visibility = System.Windows.Visibility.Visible;
                txtServer.Visibility = System.Windows.Visibility.Visible;
                txtTable.Visibility = System.Windows.Visibility.Visible;
                txtUser.Visibility = System.Windows.Visibility.Visible;
                txtPass.Visibility = System.Windows.Visibility.Visible;
                cmdCancel.Visibility = System.Windows.Visibility.Visible;
                cmdSave.Visibility = System.Windows.Visibility.Visible;
                txtServer.Text = "www.solutionob.com";
                txtUser.Text = "solut953_";
                txtTable.Text = "solut953_tdl";
                lblStatus.Content = "Configuration de la première utilisation .....";
                txtUser.Focus();
                txtUser.CaretIndex = txtUser.Text.Length;
                
            }
            else if (state == "bad")
            {
                lblPass.Visibility = System.Windows.Visibility.Visible;
                lblServer.Visibility = System.Windows.Visibility.Visible;
                lblTable.Visibility = System.Windows.Visibility.Visible;
                lblUser.Visibility = System.Windows.Visibility.Visible;
                txtServer.Visibility = System.Windows.Visibility.Visible;
                txtTable.Visibility = System.Windows.Visibility.Visible;
                txtUser.Visibility = System.Windows.Visibility.Visible;
                txtPass.Visibility = System.Windows.Visibility.Visible;
                cmdCancel.Visibility = System.Windows.Visibility.Visible;
                cmdSave.Visibility = System.Windows.Visibility.Visible;
                txtServer.Text = GCGGeneralLib.GeneralVar.Server;
                txtUser.Text = GCGGeneralLib.GeneralVar.DbUser;
                txtTable.Text = GCGGeneralLib.GeneralVar.Database;
                txtPass.Password = GCGGeneralLib.GeneralVar.DbPassword;
                lblStatus.Content = "Problème de connection, veuiller vérifier les paramètres .....";
                txtUser.Focus();
                txtUser.CaretIndex = txtUser.Text.Length;
            }
            else if (state == "ok")
            {
                MainWindow task = new MainWindow();
                task.Show();
                this.Close();   
            }
            else
            {
                lblStatus.Content = "Démarrage de T.A.G. .....";
                
            }
            
        }


        private void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            if (e.ProgressPercentage == 0)
            {
                lblStatus.Content = "Chargement des paramètres ...";
            }
            if (e.ProgressPercentage == 25)
            {
                lblStatus.Content = "Vérification de l'utilisateur ...";
            }
            if (e.ProgressPercentage == 50)
            {
                lblStatus.Content = "Tentative de connection ...";
            }
        }

        private void loadingConfig()
        {
            int serveurStartIndex = 0;
            int userStartIndex = 0;
            int passStartIndex = 0;
            int dataStartIndex = 0;

            string search = "";
            string loadedServeur = "";
            string loadedUser = "";
            string loadedPass = "";
            string loadedData = "";


            serveurStartIndex = Properties.Settings.Default.connectionString.LastIndexOf("server=") + 6;
            while (search != ";")
            {
                serveurStartIndex++;
                loadedServeur = loadedServeur + Properties.Settings.Default.connectionString.Substring(serveurStartIndex, 1);
                search = Properties.Settings.Default.connectionString.Substring(serveurStartIndex + 1, 1);
            }

            GCGGeneralLib.GeneralVar.Server = loadedServeur;
            search = "";

            userStartIndex = Properties.Settings.Default.connectionString.LastIndexOf("User Id=") + 7;
            while (search != ";")
            {
                userStartIndex++;
                loadedUser = loadedUser + Properties.Settings.Default.connectionString.Substring(userStartIndex, 1);
                search = Properties.Settings.Default.connectionString.Substring(userStartIndex + 1, 1);
            }

            GCGGeneralLib.GeneralVar.DbUser = loadedUser;
            search = "";

            passStartIndex = Properties.Settings.Default.connectionString.LastIndexOf("password=") + 8;
            while (search != ";")
            {
                passStartIndex++;

                loadedPass = loadedPass + Properties.Settings.Default.connectionString.Substring(passStartIndex, 1);
                search = Properties.Settings.Default.connectionString.Substring(passStartIndex + 1, 1);
            }
            GCGGeneralLib.GeneralVar.DbPassword = loadedPass;

            dataStartIndex = Properties.Settings.Default.connectionString.LastIndexOf("database=") + 8;


                dataStartIndex++;
                loadedData = loadedData + Properties.Settings.Default.connectionString.Substring(dataStartIndex, Properties.Settings.Default.connectionString.Length - dataStartIndex);
                GCGGeneralLib.GeneralVar.Database = loadedData;
            search = "";
            
            GCGGeneralLib.GeneralVar.FullConnectionString = Properties.Settings.Default.connectionString;
            GCGGeneralLib.GeneralVar.initialID = Properties.Settings.Default.initialID;
            GCGGeneralLib.GeneralVar.NotifyDelay = Properties.Settings.Default.notifyDelay;
            GCGGeneralLib.GeneralVar.Notify = Properties.Settings.Default.notify;
            GCGGeneralLib.GeneralVar.StartUp = Properties.Settings.Default.isStartUp;
            
        }

        private void cmdCancel_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Application.Current.Shutdown();
        }

        private void cmdSave_Click(object sender, RoutedEventArgs e)
        {

            if (testLogIn())
            {
                
                string newConnection = Properties.Settings.Default.connectionString;
                newConnection = newConnection.Replace("server=" + GCGGeneralLib.GeneralVar.Server, "server=" + txtServer.Text);
                newConnection = newConnection.Replace("User Id=" + GCGGeneralLib.GeneralVar.DbUser, "User Id=" + txtUser.Text);
                newConnection = newConnection.Replace("password=" + GCGGeneralLib.GeneralVar.DbPassword, "password=" + txtPass.Password);
                newConnection = newConnection.Replace("database=" + GCGGeneralLib.GeneralVar.Database, "database=" + txtTable.Text);
                Properties.Settings.Default.connectionString = newConnection;
                GCGGeneralLib.GeneralVar.FullConnectionString = Properties.Settings.Default.connectionString;

                object[,] EmployeArray = TEmploye.ListEmployeToStringArray();
                for (int i = 0; i < EmployeArray.GetLength(1); i++)
                {
                    if (EmployeArray[1, i].ToString() == txtUser.Text.Substring(9, 3))
                    {
                        Properties.Settings.Default.initialID = Convert.ToInt32(EmployeArray[0, i]);
                    }
                }
                Properties.Settings.Default.Save();
                loadingConfig();

                MainWindow main = new MainWindow();
                main.Show();
                this.Close();
            }
            else
            {
                MessageBox.Show("Mauvais paramétrage de la connection.");
                txtTable.Text = "solut953_tdl";
                txtUser.Text = "solut953_";
                txtServer.Text = "www.solutionob.com";
                txtPass.Password = "";
            }
        }

        private void txtPass_PreviewKeyDown_1(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {  
            if (testLogIn())
            {
                
                string newConnection = Properties.Settings.Default.connectionString;
                newConnection = newConnection.Replace("server=" + GCGGeneralLib.GeneralVar.Server, "server=" + txtServer.Text);
                newConnection = newConnection.Replace("User Id=" + GCGGeneralLib.GeneralVar.DbUser, "User Id=" + txtUser.Text);
                newConnection = newConnection.Replace("password=" + GCGGeneralLib.GeneralVar.DbPassword, "password=" + txtPass.Password);
                newConnection = newConnection.Replace("database=" + GCGGeneralLib.GeneralVar.Database, "database=" + txtTable.Text);
                Properties.Settings.Default.connectionString = newConnection;
                GCGGeneralLib.GeneralVar.FullConnectionString = Properties.Settings.Default.connectionString;
                object[,] EmployeArray = TEmploye.ListEmployeToStringArray();

                for (int i = 0; i < EmployeArray.GetLength(1); i++)
                {
                    if (EmployeArray[1, i].ToString() == txtUser.Text.Substring(9, 3))
                    {
                        Properties.Settings.Default.initialID = Convert.ToInt32(EmployeArray[0, i]);
                    }
                }
                Properties.Settings.Default.Save();
                loadingConfig();

                MainWindow main = new MainWindow();
                main.Show();
                this.Close();
            }
            else
            {
                MessageBox.Show("Mauvais paramétrage de la connection.");
                txtTable.Text = "solut953_tdl";
                txtUser.Text = "solut953_";
                txtServer.Text = "www.solutionob.com";
                txtPass.Password = "";
            }
            }
        }

        private bool testLogIn()
        {
            return GCGGeneralLib.DataBaseConnection.DbTestConnection("server=" + txtServer.Text +";User Id=" + txtUser.Text + ";password=" + txtPass.Password + ";Persist Security Info=True;database=" + txtTable.Text);
        }


    }
}
